package com.ylr.base.framework.interceptor;

import com.ylr.base.common.constant.Constant;
import com.ylr.base.common.enums.ModuleEnum;
import com.ylr.base.common.utils.IPUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by IntelliJ IDEA.
 *
 * @author wyw
 * date: 2023-04-30 21:45:59
 * className: CommonInterceptor 公共拦截器
 * version: 1.0
 * description:
 */
public class CommonInterceptor implements HandlerInterceptor {

    private static final Logger log = LoggerFactory.getLogger(CommonInterceptor.class);

    /**
     * 1、前置校验
     * @param request  http请求对象
     * @param response http响应对象
     * @param handler  目标类对象
     * @return 校验结果[true-通过 false-拒绝]
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        if (!(handler instanceof HandlerMethod)) {
            log.info("CommonInterceptor 非请求接口操作，直接放行。requestUri={}", request.getRequestURI());
            return true;
        }
        String requestIp;
        // 判断请求是不是从gateway转发过来的
        if (ModuleEnum.GATEWAY != ModuleEnum.getModuleEnum(request.getHeader(Constant.SOURCE))) {
            // 请求不来自gateway模块，优先从请求头中获取请求ip
            requestIp = request.getHeader(Constant.REQUEST_IP);
        } else {
            // 解析http请求对象，获取请求ip地址
            requestIp = IPUtils.getRequestIp(request);
        }
        log.debug("请求ip地址：{}", requestIp);
        // 设置请求ip到http请求对象中
        request.setAttribute(Constant.REQUEST_IP, requestIp);

        return true;
    }
}
